package com.company.project.component.excel.fade;

import com.company.project.component.excel.export.ExportConfigFactory;
import com.company.project.component.excel.export.FileExportor;
import com.company.project.component.excel.export.domain.common.ExportConfig;
import com.company.project.component.excel.export.domain.common.ExportResult;
import com.company.project.component.excel.export.exception.FileExportException;
import com.company.project.component.excel.importfile.ConfigParser;
import com.company.project.component.excel.importfile.ConfigurationParserFactory;
import com.company.project.component.excel.importfile.FileImportExecutor;
import com.company.project.component.excel.importfile.domain.MapResult;
import com.company.project.component.excel.importfile.domain.common.Configuration;
import com.company.project.component.excel.importfile.exception.FileImportException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * IntelliJ IDEA.
 * User: lwb
 * Date: 2018/1/18
 * Time: 16:44
 * function:
 */
public class ExcelUtil
{


    private static final String EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";

    /***
     * <pre>
     * 取得Workbook对象(xls和xlsx对象不同,不过都是Workbook的实现类)
     *   xls:HSSFWorkbook
     *   xlsx：XSSFWorkbook
     * @param request
     * @return
     * @throws java.io.IOException
     * </pre>
     */
    public static Workbook getWorkbook(HttpServletRequest request) throws IOException
    {

        if (request instanceof MultipartHttpServletRequest)
        {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            Set<Map.Entry<String, MultipartFile>> set = fileMap.entrySet();
            Iterator<Map.Entry<String, MultipartFile>> it = set.iterator();

            if (it.hasNext())
            {
                Map.Entry<String, MultipartFile> entry = it.next();
                MultipartFile multipartFile = entry.getValue();
                String name = multipartFile.getOriginalFilename();
                InputStream in = multipartFile.getInputStream();
                Workbook workbook = null;
                if (name.endsWith(EXTENSION_XLS)) {
                    workbook = new HSSFWorkbook(in);
                } else if (name.endsWith(EXTENSION_XLSX)) {
                    workbook = new XSSFWorkbook(in);
                } else {
                    throw new FileFormatException("传入的文件不是excel");
                }
                return workbook;
            }
        }
        return  null;
    }


    /**
     * 读取excel文件内容
     *
     * @param workbook
     * @throws java.io.FileNotFoundException
     * @throws org.apache.xmlbeans.impl.piccolo.io.FileFormatException
     */
    public static void readExcel(Workbook workbook) throws FileNotFoundException, FileFormatException
    {

        try
        {
            // 读文件 一个sheet一个sheet地读取
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++)
            {
                Sheet sheet = workbook.getSheetAt(numSheet);
                if (sheet == null) {
                    continue;
                }
                System.out.println("=======================" + sheet.getSheetName() + "=========================");

                int firstRowIndex = sheet.getFirstRowNum();
                int lastRowIndex = sheet.getLastRowNum();

                // 读取首行 即,表头
                Row firstRow = sheet.getRow(firstRowIndex);
                for (int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) {
                    Cell cell = firstRow.getCell(i);
                    String cellValue = getCellValue(cell, true);
                    System.out.print(" " + cellValue + "\t");
                }
                System.out.println("");

                // 读取数据行
                for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);// 当前行
                    int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
                    int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
                    for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++)
                    {
                        Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
                        String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
                        System.out.print(currentCellValue + "\t");
                    }
                    System.out.println("");
                }
                System.out.println("======================================================");
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 取单元格的值
     *
     * @param cell       单元格对象
     * @param treatAsStr 为true时，当做文本来取值 (取到的是文本，不会把“1”取成“1.0”)
     * @return
     */
    public static String getCellValue(Cell cell, boolean treatAsStr)
    {
        if (cell == null) {
            return "";
        }


        if (treatAsStr) {
            // 虽然excel中设置的都是文本，但是数字文本还被读错，如“1”取成“1.0”
            // 加上下面这句，临时把它当做文本来读取
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }


        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return String.valueOf(cell.getStringCellValue().toString());
        }
    }


    /***
     *
     * ===========================================================================================================
     *
     *
     */

    /**
     *
     *
     * @param request
     * @param configName 解析excel的配置文件的路径 如在resource下的excel文件夹下的“config.xml”
     * @return
     * @throws IOException
     * @throws FileImportException
     */
    public static List<Map> importExcelData(HttpServletRequest request , String configName)
            throws IOException, FileImportException
    {

        if (request instanceof MultipartHttpServletRequest)
        {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            Set<Map.Entry<String, MultipartFile>> set = fileMap.entrySet();
            Iterator<Map.Entry<String, MultipartFile>> it = set.iterator();

            if (it.hasNext())
            {
                Map.Entry<String, MultipartFile> entry = it.next();
                MultipartFile multipartFile = entry.getValue();
                System.out.println("multipartFile.getOriginalFilename():" + multipartFile.getOriginalFilename());

                List<Map> mapList = new ArrayList<>();
                ConfigParser configParser = ConfigurationParserFactory.getConfigParser(Configuration.ParserType.XML);
                Configuration configuration = configParser.getConfig(ExcelUtil.class.getResourceAsStream("/excel/import/"+configName));
                MapResult mapResult = (MapResult) FileImportExecutor.importFile(configuration, multipartFile.getInputStream() , multipartFile.getOriginalFilename());
                mapList = mapResult.getResult();
                return mapList;
            }
        }

        return  null;
    }

    /**
     * @param importFile 选中的excel文件
     * @param configName   解析excel的配置文件的路径 如在resource下的excel文件夹下的“config.xml”
     * @throws IOException
     * FileImportException
     */
    public static List<Map> importExcelData(File importFile , String configName)
            throws IOException, FileImportException
    {
        Configuration configuration = null;
        List<Map> mapList = new ArrayList<>();
        ConfigParser configParser = ConfigurationParserFactory.getConfigParser(Configuration.ParserType.XML);
        configuration = configParser.getConfig(ExcelUtil.class.getResourceAsStream("/excel/import/"+configName));
        MapResult mapResult = (MapResult) FileImportExecutor.importFile(configuration, importFile, importFile.getName());
        mapList = mapResult.getResult();
        return mapList;
    }

    /**
     *
     * @param list 里面的值可以是Map键值对
     * @param configName 解析excel的配置文件的路径 如在resource下的excel文件夹下的“config.xml”
     * @param outputStream
     * @throws FileExportException
     * @throws IOException
     */
    public static void  exportExcelWithList(List<Map> list,  String configName , OutputStream outputStream)
            throws FileExportException, IOException
    {

        ExportConfig exportConfig = ExportConfigFactory.getExportConfig(ExcelUtil.class.getResourceAsStream("/excel/export/"+configName));
        ExportResult exportResult = FileExportor.getExportResult(exportConfig, list);
        exportResult.export(outputStream);

    }

    /**
     *
     * @param list 里面的值可以是Map键值对
     * @param configName 解析excel的配置文件的路径 如在resource下的excel文件夹下的“config.xml”
     * @param response
     * @throws FileExportException
     * @throws IOException
     */
    public static void  exportExcelWithList(List<Map> list,  String configName , String fileName ,HttpServletResponse response) throws FileExportException, IOException {
        OutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        exportExcelWithList(list,   configName ,  outputStream);
    }

}
